# Created by 黄景涛
# DATE: 2024/11/13

import requests
import math

from config import settings

cfg = settings.cfg
headers = settings.headers
fk = settings.fk


# full_url
def search_users_from_org(org_id: int) -> list[tuple]:
    """ 按组织id查询所有用户 """
    # 全局的session对象
    session = requests.session()
    full_users_list_url = cfg.get('user_manager').get('user_base_url') + cfg.get('user_manager').get(
        'search_users_list_route') + f'/{org_id}/profiles/'

    users = []
    page = 1
    page_size = 100
    params = {
        "page_size": page_size,
        "page": page,
        "recursive": True
    }

    try:
        resp = session.get(full_users_list_url, params=params, headers=headers)
        all_counts = resp.json().get('data').get('count')
        all_pages = math.ceil(all_counts / page_size)
        for p in range(1, all_pages + 1):
            param = {
                "page_size": page_size,
                "page": p,
                "recursive": True
            }
            resp = session.get(full_users_list_url, params=param, headers=headers)
            users_list = resp.json().get('data').get('data')
            for user in users_list:
                users.append((user['id'], user['display_name'], user['username']))
    except:
        raise Exception(f'查询组织{org_id}的用户列表失败')
    return users


if __name__ == '__main__':
    org_id = 29879
    users = search_users_from_org(org_id)
    print(len(users), f'\n{users}')
